<script setup lang="ts">
import { Edit as EditIcon, Key as KeyIcon } from '@element-plus/icons-vue'
import { ElMessageBox, type FormInstance } from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import EncryptDecrypt, { HandleType } from './components/EncryptDecrypt'

const formRef = ref<FormInstance>()
const form = reactive({
  secret: '',
  content: '',
})
const rules = {
  secret: { required: true, message: '请输入密钥' },
  content: { required: true, message: '请输入待加解密内容' },
}

async function handleEncryptDecrypt(type: HandleType) {
  const valid = await formRef.value?.validate().catch((res) => !res)
  if (!valid) return

  ElMessageBox({
    title: '加解密结果',
    closeOnClickModal: false,
    message: h(EncryptDecrypt, { type, ...form }),
  })
}
</script>

<template>
  <ElConfigProvider
    :locale="zhCn"
    :button="{ autoInsertSpace: true }"
  >
    <ElContainer class="container">
      <ElMain>
        <ElCard
          class="form-card"
          header="加解密"
        >
          <ElForm
            ref="formRef"
            :model="form"
            :rules="rules"
          >
            <ElFormItem prop="secret">
              <ElInput
                v-model.trim="form.secret"
                type="password"
                :show-password="false"
                placeholder="请输入密钥"
                :prefix-icon="KeyIcon"
                :clearable="true"
              />
            </ElFormItem>
            <ElFormItem prop="content">
              <ElInput
                v-model.trim="form.content"
                placeholder="请输入待加解密内容"
                :prefix-icon="EditIcon"
                :clearable="true"
              />
            </ElFormItem>
            <ElRow
              class="actions"
              :gutter="10"
            >
              <ElCol :span="12">
                <ElButton
                  type="primary"
                  @click="handleEncryptDecrypt(HandleType.encrypt)"
                >
                  加密
                </ElButton>
              </ElCol>
              <ElCol :span="12">
                <ElButton
                  type="danger"
                  @click="handleEncryptDecrypt(HandleType.decrypt)"
                >
                  解密
                </ElButton>
              </ElCol>
            </ElRow>
          </ElForm>
        </ElCard>
      </ElMain>
    </ElContainer>
  </ElConfigProvider>
</template>

<style scoped lang="scss">
.container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(#409eff, #409eff 30%, #f5f7fa 30%, #f5f7fa 100%);
  overflow: hidden;

  .form-card {
    position: relative;
    max-width: 400px;
    margin: 15vh auto;
    border-color: transparent;

    .actions {
      :deep(.el-button) {
        width: 100%;
      }
    }
  }
}
</style>
